<template>
  <div id="cornerComment" v-if="detailVisible">
    <div class="cornerComment-in">
      <div class="cornerComment-in-title">
        <span>规则详情</span>
        <span class="el-icon-circle-close close-Btn-line" @click="closePOpup"></span>
      </div>
      <div class="commentBody ruleEdit-body">
        <el-form ref="form" :model="form" label-width="100px">
          <el-row>
            <el-col :span="24">
              <el-form-item label="规则名称:" prop="name" required :show-message="false">
                <el-input v-model="form.name" placeholder="规则名称"/>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开始时间:" prop="beginTime" required :show-message="false">
                <el-time-picker
                  v-model="form.beginTime"
                  format="HH:mm:ss"
                  value-format="HH:mm:ss"
                  :picker-options="{
      selectableRange: '00:00:00 - 23:59:59'
    }"
                  placeholder="开始时间">
                </el-time-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="结束时间:" prop="endTime" required :show-message="false">
                <el-time-picker
                  v-model="form.endTime"
                  format="HH:mm:ss"
                  value-format="HH:mm:ss"
                  :picker-options="{
      selectableRange: '00:00:00 - 23:59:59'
    }"
                  placeholder="结束时间">
                </el-time-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否警报:" prop="isAlarm" required :show-message="false">
                <el-radio-group v-model="form.isAlarm">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="报警次数:" prop="alarmNumber" required :show-message="false">
                <el-input v-model="form.alarmNumber" placeholder="报警次数"/>
                每日警报的最大数量，超过此数量将不再提示
              </el-form-item>
            </el-col>
            <el-col :span="18">
              <el-form-item label="操作说明:" prop="commandId" required :show-message="false">
                <el-button size="mini" plain @click="showRulevisible=true">选择操作说明</el-button>
                {{ ruleOption ? `【${ruleOption.name}】` : '' }}
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <el-divider>条件 {{ lineCon }}</el-divider>
        <div class="term-body">
          <div class="term-list" v-for="(item, index) in ruleList" :key="index">
            <div class="term-list-left">
              <el-select
                v-model="item.tage"
                placeholder="combination"
                style="width: 100px"
                size="small"
                v-if="index"
                popper-class="select-popper"
                @change="getChangeFn"
              >
                <el-option
                  v-for="item in dict.type.sys_montage"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>
            <div class="term-list-right">
              <div class="term-list-right-title">
                条件{{ tageList[index] }}
              </div>
              <div class="term-list-right-content">
                <el-select v-model="item.key" placeholder="Select Field" class="w-150 mr-10" size="small"
                           @change="getValueType(index)">
                  <el-option
                    v-for="item_ in keyList"
                    :key="item_.name"
                    :label="item_.name"
                    :value="item_.name">
                  </el-option>
                </el-select>
                <el-select
                  v-model="item.type"
                  placeholder="Judging conditions"
                  clearable
                  popper-class="select-popper"
                  style="width: 140px"
                  size="small"
                >
                  <el-option
                    v-for="item_type in dict.type.sys_condition"
                    :key="item_type.value"
                    :label="item_type.label"
                    :value="item_type.value"
                  />
                </el-select>
                <el-input v-model="item.value" placeholder="判断值" maxlength="30" class="w-150 ml-10" size="small"
                          v-if="item.keyType!=='switch'"/>
                <el-select
                  v-model="item.value"
                  placeholder="Judging conditions"
                  clearable
                  popper-class="select-popper"
                  style="width: 140px"
                  size="small"
                  class="ml-10"
                  v-else
                >
                  <el-option
                    v-for="item_s in item.selectList"
                    :key="item_s"
                    :label="item_s"
                    :value="item_s"
                  />
                </el-select>
              </div>
              <div class="term-list-right-icon">
                <i class="el-icon-remove-outline" v-if="index || ruleList.length>1" @click="deleteList(index)"></i>
                <i class="el-icon-circle-plus-outline" v-if="index+1==ruleList.length && ruleList.length!==3"
                   @click="addList(index)"></i>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="cornerComment-in-footer">
        <el-button size="small" @click="closePOpup">取消</el-button>
        <el-button size="small" type="primary" @click="checkJsonFn">确认</el-button>
      </div>
    </div>
    <commandBox :visible.sync="showRulevisible" @getRule="getRule"></commandBox>
  </div>
</template>

<script>
import commandBox from '@/components/command'
import {getRules, addRules, updateRules} from "@/api/system/rules";
import {getCategory} from "@/api/system/category";
import {getCommand} from "@/api/system/command";

export default {
  props: ['visible', 'ruleId', 'deviceDetail', 'typeEdit', 'ruleType'],
  name: "deviceDetail",
  components: {commandBox},
  dicts: ['sys_montage', 'sys_condition'],
  data() {
    return {
      detailVisible: false,
      ruleList: [
        {
          key: '', // 字段名
          value: '',// 判断值
          type: '', // 判断类型
          tage: 'and', // 拼接
          keyType: '',
          selectList: []
        }
      ],
      form: {
        name: '',
        cateId: '', // 分类id
        type: 0, // 1分类2设备
        andCondition: '', // and 数据
        orCondition: '', // or 数据
        allCondition: '', // 前端自定义数据
        beginTime: '', // 规则开始时间
        endTime: '', // 规则结束时间
        commandId: '',
        deviceId: 0,
        isAlarm: 1,//  是否告警
        alarmNumber: 0 // 每日告警数
      },
      showRulevisible: false,
      ruleOption: null,
      tageList: ['A', 'B', 'C'],
      lineCon: 'A',
      keyList: [],
      flag: true
    }
  },
  watch: {
    visible() {
      this.detailVisible = this.visible
      if (!this.visible) {
        this.ruleList = [
          {
            key: '',
            value: '',
            type: '',
            tage: 'and', // 拼接
            keyType: '',
            selectList: []
          }
        ]
        this.ruleOption = null
        this.keyList = []
        this.lineCon = 'A'
        this.form = {
          name: '',
          cateId: '', // 分类id
          type: 0, // 1分类2设备
          andCondition: '', // and 数据
          orCondition: '', // or 数据
          allCondition: '', // 前端自定义数据
          beginTime: '', // 规则开始时间
          endTime: '', // 规则结束时间
          commandId: '',
          deviceId: 0,
          isAlarm: 1,//  是否告警
          alarmNumber: '' // 每日告警数
        }
      } else {
        this.form.type = this.typeEdit === 'cate' ? 1 : 2;
        this.getCategoryFn()
        if (this.ruleId) {
          this.getRuleDetail()
        }
      }
    }
  },
  methods: {
    getRuleDetail() {
      getRules(this.ruleId).then(res => {
        let {data} = res
        this.form.name = data.name
        this.form.beginTime = data.beginTime
        this.form.endTime = data.endTime
        this.form.isAlarm = data.isAlarm //  是否告警
        this.form.alarmNumber = data.alarmNumber // 每日告警数
        this.getRuleLineFn(data.commandId)
        this.ruleList = JSON.parse(data.allCondition)
      })
    },
    getCategoryFn() {
      getCategory(this.deviceDetail.category).then(res => {
        let {data} = res
        // this.keyList = JSON.parse(JSON.stringify(data.categoryDataConfigList))
        this.keyList = JSON.parse(data.downData)
      })
    },
    getRuleLineFn(id) {
      getCommand(id).then(res => {
        let {data} = res
        this.ruleOption = JSON.parse(JSON.stringify(data))
      })
    },
    addList() {
      this.ruleList.push({
        key: '', // 字段名
        value: '',// 判断值
        type: '', // 判断类型
        tage: 'and' // 拼接
      })
      this.getChangeFn()
    },
    deleteList(index) {
      this.ruleList.splice(index, 1)
      this.getChangeFn()
    },
    getChangeFn() {
      if (this.ruleList.length === 1) {
        this.lineCon = 'A'
      } else if (this.ruleList.length === 2) {
        if (this.ruleList[1].tage === 'and') {
          this.lineCon = 'A & B'
        } else {
          this.lineCon = 'A | B'
        }
      } else if (this.ruleList.length === 3) {
        if (this.ruleList[1].tage === 'and' && this.ruleList[2].tage === 'and') {
          this.lineCon = '( A & B ) & C'
        }
        if (this.ruleList[1].tage === 'and' && this.ruleList[2].tage === 'or') {
          this.lineCon = '( A & B ) | C'
        }
        if (this.ruleList[1].tage === 'or' && this.ruleList[2].tage === 'and') {
          this.lineCon = 'A | ( B & C )'
        }
        if (this.ruleList[1].tage === 'or' && this.ruleList[2].tage === 'or') {
          this.lineCon = '( A | B ) | C'
        }
      }
    },
    getRule(option) {
      this.ruleOption = JSON.parse(JSON.stringify(option))
    },
    deleteSmallList(index, small) {
      this.jsonList[index].list.splice(small, 1)
    },
    checkJsonFn() {
      console.log('form:', this.form)
      let length_ = this.ruleList.length
      let data_Json = JSON.parse(JSON.stringify(this.ruleList))
      if (!this.form.name) {
        this.$message.error('填写规则名称')
        return
      }
      if (!this.form.beginTime) {
        this.$message.error('选择规则开始时间')
        return
      }
      if (!this.form.endTime) {
        this.$message.error('选择规则规则时间')
        return
      }
      if (!this.ruleOption) {
        this.$message.error('选择执行指令')
        return
      }

      let state = true
      for (let item of data_Json) {
        if (!item.key || !item.value || !item.type) {
          state = false
        }
      }
      if (!state) {
        this.$message.error('完善规则信息')
        return
      }

      let or_condition = []
      let and_condition = []
      if (length_ === 1) {
        and_condition.push(data_Json[0])
      } else if (length_ === 2) {
        if (data_Json[1].tage === 'and') {
          and_condition = data_Json
        } else {
          or_condition = data_Json
        }
      } else if (length_ === 3) {
        if (data_Json[1].tage === 'or' && data_Json[2].tage === 'or') {
          or_condition = data_Json
        }
        if (data_Json[1].tage === 'or' && data_Json[2].tage === 'and') {
          or_condition.push(data_Json[0])
          and_condition.push(data_Json[1])
          and_condition.push(data_Json[2])
        }
        if (data_Json[1].tage === 'and' && data_Json[2].tage === 'and') {
          and_condition = data_Json
        }
        if (data_Json[1].tage === 'and' && data_Json[2].tage === 'or') {
          or_condition.push(data_Json[2])
          and_condition.push(data_Json[0])
          and_condition.push(data_Json[1])
        }
      }
      for (let item of or_condition) {
        delete item.tage
        delete item.keyType
        delete item.selectList
      }
      for (let item of and_condition) {
        delete item.tage
        delete item.keyType
        delete item.selectList
      }
      console.log('最后提交的数据：', or_condition, and_condition)
      let data_ = JSON.parse(JSON.stringify(this.form))
      let that = this
      if (and_condition.length) {
        data_.andCondition = JSON.stringify(and_condition)
      } else {
        delete data_.andCondition
      }
      if (or_condition.length) {
        data_.orCondition = JSON.stringify(or_condition)
      } else {
        delete data_.orCondition
      }
      data_.allCondition = JSON.stringify(this.ruleList)
      data_.commandId = this.ruleOption.id
      data_.deviceId = this.typeEdit !== 'cate' ? this.deviceDetail.id : 0
      data_.cateId = this.typeEdit === 'cate' ? this.deviceDetail.category : 0
      // console.log('data_', data_)
      // let state_ = 1
      // if(state){
      //   return
      // }
      if (!this.flag) {
        return
      }
      this.flag = false
      if (this.ruleId && this.ruleType === 'edit') {
        data_.id = this.ruleId
        updateRules(data_).then(res => {
          if (res.code === 200) {
            this.$emit('initList')
            this.$message.success(res.msg)
            this.closePOpup()
          } else {
            this.$message.error(res.msg)
          }
        })
      } else {
        addRules(data_).then(res => {
          if (res.code === 200) {
            this.$emit('initList')
            this.$message.success(res.msg)
            this.closePOpup()
          } else {
            this.$message.error(res.msg)
          }
        })
      }
      setTimeout(() => {
        that.flag = true
      }, 1000)
    },
    saveJsonFn() {
      console.log('jsonList:', this.ruleList)
      // key: '', // 字段名
      //   value: '',// 判断值
      //   type: '', // 判断类型
      //   tage: 'and' // 拼接
      let state = true
      let json_list = [] // 命令值
      for (let index in this.ruleList) {
        let item = this.ruleList[index]
        json_list.push(this.getLineFn(item).join(' '))
        if (item.key || item.value || item.type || item.tage) {
          state = false
        }
      }
      // if(!state){
      //   this.$message.error('完善条件值，不能为空')
      //   return
      // }
      if (this.ruleList.length === 2) {
        json_list.splice(1, 0, this.ruleList[1].tage);

      } else if (this.ruleList.length === 3) {
        if (this.ruleList[1].tage === 'and') {
          json_list.unshift('(')
          json_list.splice(3, 0, ')')
          json_list.splice(2, 0, this.ruleList[1].tage)
          json_list.splice(5, 0, this.ruleList[2].tage)
        }
        if (this.ruleList[1].tage === 'or') {
          if (this.ruleList[1].tage === 'or' && this.ruleList[2].tage === 'or') {
            json_list.unshift('(')
            json_list.splice(3, 0, ')')
            json_list.splice(2, 0, this.ruleList[1].tage)
            json_list.splice(5, 0, this.ruleList[2].tage)
          }
          if (this.ruleList[1].tage === 'or' && this.ruleList[2].tage === 'and') {
            json_list.push(')')
            json_list.splice(1, 0, '(')
            json_list.splice(1, 0, this.ruleList[1].tage)
            json_list.splice(4, 0, this.ruleList[2].tage)
          }
        }
      }
    },
    getLineFn(row) {
      let key_ = ['key', 'type', 'value']
      let val_ = []
      for (let item of key_) {
        val_.push(row[item])
      }
      return val_
    },
    closePOpup() {
      this.$emit('update:visible', false)
    },
    getValueType(index) {
      let option_ = JSON.parse(JSON.stringify(this.ruleList[index]))
      for (let item of this.keyList) {
        if (item.name === option_.key) {
          option_.keyType = item.keyType
          if (item.keyType === 'switch') {
            option_.value = ''
            option_.selectList = item.type.split('/')
          }
        }
      }
      this.$set(this.ruleList, index, option_)
    }
  }
}
</script>

<style scoped>
.Json-list {
  border: 1px solid #eee;
  padding: 10px;
}

.Json-list-line {
  display: flex;
  align-items: center;
}

.w-150 {
  width: 150px;
}

.ml-10 {
  margin-left: 10px;
}

.mr-10 {
  margin-right: 10px;
}

.mb-10 {
  margin-bottom: 10px;
}

#cornerComment {
  height: 100vh;
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, .5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 999999;
}

.cornerComment-in {
  width: 760px;
  height: 70%;
  background: #fff;
  display: flex;
  flex-direction: column;
  border-radius: 5px;
}

.cornerComment-in-title {
  height: 50px;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #ddd;
  font-size: 24px;
}

.cornerComment-in-title span {
  padding: 0 10px;
}

.cornerComment-in-title span:first-child {
  flex: 1;
  font-size: 16px;
}

.cornerComment-in-footer {
  height: 50px;
  border-top: 1px solid #ddd;
  display: flex;
  align-items: center;
  padding: 0 10px;
  justify-content: center;
}

.commentBody {
  padding: 10px;
  flex: 1;
  overflow-y: auto;
}

.close-Btn-line {
  cursor: pointer;
}

.Json-small-list {
  background: #eee;
  padding: 10px;
  margin-top: 10px;
}

.term-list {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.term-list-left {
  width: 100px;
}

.term-list-right {
  flex: 1;
  display: flex;
}

.term-list-right-title {
  width: 70px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

.term-list-right-content {
  display: flex;
  align-items: center;
}

.term-list-right-icon {
  width: 100px;
  display: flex;
  align-items: center;
  justify-content: start;
  padding-left: 20px;
}

.term-list-right-icon i {
  font-size: 26px;
  margin-right: 10px;
  cursor: pointer;
}

.term-list-right-icon i.el-icon-remove-outline {
  color: #E65D6E;
}

.term-list-right-icon i.el-icon-circle-plus-outline {
  color: #00afff;
}
</style>
